package com.web.web;

import static com.web.message.ErrorMessage.*;

import java.io.*;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.database.daos.IProjectDao;
import com.database.objects.*;
import com.metrics.ctrls.IReportCtrl;
import com.metrics.objects.Metric;
import com.opensymphony.xwork2.ActionSupport;
import com.web.utils.SingletonData;

public class ReportAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private IProjectDao projectDao;

	private IReportCtrl reportCtrl;

	private SingletonData singletonData;

	private Project project;

	private String repository;

	private Metric metric;

	private Integer keyData;

	public void validateReport() {
		if (repository == null || repository.equals("")) {
			addActionError(errorRequiredField("Repository"));
		}
		if (metric == null) {
			addActionError(errorRequiredField("Metric"));
		}
	}

	public String reportMetrics() {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/csv");
			response.setHeader("Content-Disposition", "attachment; filename=report.txt");

			project = projectDao.getByName(project.getName());
			Repository repositoryProject = project.getRepository(repository);
			reportCtrl.generateMetricsReport(response.getOutputStream(), project, repositoryProject, metric);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("Ocurrio un error generando el archivo");
		}
		return NONE;
	}

	public String reportModel() {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/csv");
			response.setHeader("Content-Disposition", "attachment; filename=report.txt");

			String valueData = singletonData.getValue(keyData);
			reportCtrl.generateModelReport(response.getOutputStream(), valueData);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}

	public void setProjectDao(IProjectDao projectDao) {
		this.projectDao = projectDao;
	}

	public void setReportCtrl(IReportCtrl reportCtrl) {
		this.reportCtrl = reportCtrl;
	}

	public void setSingletonData(SingletonData singletonData) {
		this.singletonData = singletonData;
	}

	public void setProject(Project project) {
		this.project = project;
	}

	public void setRepository(String repository) {
		this.repository = repository;
	}

	public void setMetric(String metric) {
		this.metric = metric != null && !metric.equals("") ? Metric.valueOf(metric.replace(" ", "_")) : null;
	}

	public void setKeyData(Integer keyData) {
		this.keyData = keyData;
	}

}